package com.shenzhenai.it_hei_ma_mythreadtest.test7;

import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.Callable;

/**
 * @author huangzehui
 * @date 2025/9/1 13:21 周一
 * @description https://www.bilibili.com/video/BV1LG4y1T7n2?spm_id_from=333.788.videopod.episodes&vd_source=e07cc8cc94eb22bd76722071b03cd199&p=27
 */
public class MyCallable implements Callable<Integer> {

    ArrayList<Integer> list;


    public MyCallable(ArrayList<Integer> list) {
        this.list = list;
    }

    private String getName() {
        return Thread.currentThread().getName();
    }


    @Override
    public Integer call() throws Exception {
        // 1. 循环
        // 2. 同步代码块
        // 3. 判断
        // 4. 判断
        ArrayList<Integer> boxList = new ArrayList<>();

        while (true) {
            synchronized (com.shenzhenai.it_hei_ma_mythreadtest.test5.MyThread.class) {
                if (list.isEmpty()) {
                    StringBuilder str = new StringBuilder();
                    int max = 0;
                    int sum = 0;
                    for (Integer i : boxList) {
                        str.append(",").append(i);
                        if (max == 0) {
                            max = i;
                        } else {
                            max = Math.max(max, i);
                        }
                        sum += i;
                    }

                    if (!str.isEmpty()) {
                        str.deleteCharAt(0);
                    }


                    System.out.println(getName() + "总共产生了" + boxList.size() + "个奖项。分别为：" + str + " 最高奖项为：" + max + " 总金额：" + sum);

                    break;
                } else {
                    // 继续抽奖
                    // Random 或 Colections.shuffle 都可以达到随机
                    // Colections.shuffle 是通过打乱集合的方式
                    Collections.shuffle(list);
                    int price = list.remove(0);
//                    System.out.println(getName() + "又产生了一个 " + price + " 元大奖");
                    if ("抽奖箱1".equals(getName())) {
                        boxList.add(price);
                    } else {
                        boxList.add(price);
                    }
                }
            }

            try {
                // 这里睡一下，可以让多个线程抢占cpu的执行权更均匀
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


        if (boxList.size()  ==  0){
            return null;
        }

        return Collections.max(boxList);
    }
}
